package com.soriya.nestlive.im;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketAddress;

@Slf4j
@Component
public class TcpServer {

    @Autowired
    private LiveChatHandler liveChatHandler;

    public void start(int port) {
        NioEventLoopGroup bootGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        new ServerBootstrap()
                .group(bootGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("decoder", new StringDecoder());
                        socketChannel.pipeline().addLast("encoder", new StringEncoder());
                        socketChannel.pipeline().addLast(liveChatHandler);
                    }
                })
                .bind(port)
                .addListener((ChannelFutureListener) channelFuture -> {
                    SocketAddress address = channelFuture.channel().localAddress();
                    log.info("TcpServer running at {}:{}", address, port);
                });
    }

}
